//
//  CategoryViewController.m
//  StandardizedProduct
//
//  Created by 宁宁 on 16/6/21.
//  Copyright © 2016年 ym. All rights reserved.
//

#import "CategoryViewController.h"

#import "CategoryDetailViewController.h"//商品分类详情页Controller

#import "GoodsDetailViewController.h"//商品明细Controller

#import "CategoriesCollectionViewCell.h"//collectionViewCell

#import "HomeCategroyModel.h"//分类model
#import "GoodsModel.h"//分类xx-model

#define TableViewWidth SCREEN_WIDTH / 4
#define TableViewCellHeight 50

@interface CategoryViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
/**左边分类TableView*/
@property (nonatomic, strong) UITableView *categoryTableView;
/**右边分类详情CollectionView*/
@property (nonatomic, strong) UICollectionView *categoryCollectionView;

@end

@implementation CategoryViewController
{
    NSMutableArray *_categoryTableArray;//TableView数据
    
    NSMutableArray *_categoryCollectionArray;//CollectionView数据
}

 static NSString *const TableViewCellID = @"TableViewCell";
 static NSString *const CategoriesCollectionViewCellID = @"CategoriesCollectionViewCell";


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [_categoryTableArray removeAllObjects];
    //网络请求
    [self requestCategroy];
 
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"分类";
    UIBarButtonItem *back = [[UIBarButtonItem alloc] init];
    back.title = @"返回";
    self.navigationItem.backBarButtonItem = back;
    
    
    _categoryTableArray = [NSMutableArray array];
    _categoryCollectionArray = [NSMutableArray array];
    
    //网络请求
//    [self network];
    
    //创建TableView
    [self registerTableView];
    //创建CollectionView
    [self createCollectionView];
}
#pragma mark === 创建TableView ===
- (void)registerTableView{
    
    [self.categoryTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:TableViewCellID];
}

#pragma mark === 创建CollectionView ===
- (void)createCollectionView{
    
    [self.categoryCollectionView registerNib:[UINib nibWithNibName:@"CategoriesCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:CategoriesCollectionViewCellID];
}

#pragma mark === TableViewDelegate ===
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _categoryTableArray.count;
}
//Reusable
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableViewCellID];
    HomeCategroyModel *model = _categoryTableArray[indexPath.row];
    cell.textLabel.text = model.Name;
    cell.textLabel.font = [UIFont systemFontOfSize:16];
    cell.textLabel.adjustsFontSizeToFitWidth = YES;
    cell.textLabel.highlightedTextColor = APPCOLOR;
    cell.backgroundColor = BackgroundCOLOR;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, TableViewWidth, TableViewCellHeight)];
    view.backgroundColor = [UIColor whiteColor];
    UIView *stick = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 6, TableViewCellHeight)];
    stick.backgroundColor = APPCOLOR;
    [view addSubview:stick];
    cell.selectedBackgroundView = view;

    return cell;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return TableViewCellHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.searchBar resignFirstResponder];

    HomeCategroyModel *cateModel = _categoryTableArray[indexPath.row];
    //将TableView被选中行滑动到最中间
    [_categoryTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    [self requestCategoryDetail:cateModel.Id];
}

#pragma mark === CollectionViewDelegate ===
//item数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _categoryCollectionArray.count;
}
//Reusable
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CategoriesCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CategoriesCollectionViewCellID forIndexPath:indexPath];
    GoodsModel *classify = _categoryCollectionArray[indexPath.item];
    cell.title.text =  classify.Title;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:classify.ProductSmallUrl] placeholderImage:[UIImage imageNamed:@"XQYicon_000"]];
    return cell;
}
//距四周边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
//item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((SCREEN_WIDTH - TableViewWidth) / 3, (SCREEN_WIDTH - TableViewWidth) / 3 + 40);
}
//被选择时
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self.searchBar resignFirstResponder];
    NSLog(@"%@", _categoryCollectionArray[indexPath.item]);
    GoodsModel *classify = _categoryCollectionArray[indexPath.item];
    GoodsDetailViewController *detail = [[GoodsDetailViewController alloc] init];
    detail.modelId = classify.Id;
    detail.modelProductCode = classify.ProductCode;
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.searchBar resignFirstResponder];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.searchBar resignFirstResponder];
}

#pragma mark === 网络请求 ===
//TableView
- (void)requestCategroy{
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"7494/api/Product/GetCateDt?" withParaments:nil withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"商品类目 : %@", object);
        if ([object[@"Code"] isEqualToString:@"0"]) {
            if (!_categoryTableArray) {
                _categoryTableArray = [NSMutableArray array];
            }else{
                [_categoryTableArray removeAllObjects];
            }
            for (NSDictionary *dic in object[@"Rows"]) {
                HomeCategroyModel *model = [HomeCategroyModel parseUserWithDictionary:dic];
                [_categoryTableArray addObject:model];
            }
            if (_categoryTableArray.count > 0) {
                [_categoryTableView reloadData];
            }
            
        }
        //默认选中第一个cell
        [_categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        
        HomeCategroyModel *model = _categoryTableArray[0];
        [self requestCategoryDetail:model.Id];
        
    } withFailureBlock:^(NSError *error) {
        NSLog(@"商品类目网络请求失败 : %@", error);
    } progress:nil];
    
}
//CollectionView
- (void)requestCategoryDetail:(NSString *)index{
    
    NSDictionary *paraments = @{
                                @"productCat"      : index,
                                @"brand"           : @"0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,424,425,426,427,428,429",
                                @"currentpage"     : @"1",
                                @"pagesize"        : @"40",
                                
                                @"query"           : @"",
                                @"pricelow"        : @"0",
                                @"pricehigh"       : @"0",
                                @"marketPriceLow"  : @"0",
                                @"marketPriceHigh" : @"0",
                                
                                @"sortfield"       : @"all",
                                @"desc"            : @"true",
                                @"pw"              : @"-1"
                                };
    
    [NetWorkManager requestWithType:HttpRequestTypeGet withMethodName:@"12082/api/BOMProductExtend/SearchPorductByCondition?" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"-分类详情---- %@", object);
        if (isKindOfNSDictionary(object[@"Rows"])) {
            if (!_categoryCollectionArray) {
                _categoryCollectionArray = [NSMutableArray array];
            }else{
                [_categoryCollectionArray removeAllObjects];
            }
            
            NSDictionary *dict = object[@"Rows"];
            if (isKindOfNSArray([dict objectForKey:@"product"])) {
                NSArray *array = [dict objectForKey:@"product"];
                if (array.count)
                {
                    for (NSDictionary *smDic in array) {
                        GoodsModel *goods  = [GoodsModel parseUserWithDictionary:smDic];
                        
                        [_categoryCollectionArray addObject:goods];
                    }
                    [_categoryCollectionView reloadData];
                }
            }
        }
    } withFailureBlock:^(NSError *error) {
        NSLog(@"商品搜索网络请求失败 : %@", error);
    } progress:nil];
    
}

- (UITableView *)categoryTableView{
    if (!_categoryTableView) {
        _categoryTableView= [[UITableView alloc]initWithFrame:CGRectMake(0, 108, TableViewWidth, SCREEN_HEIGHT - 64 - 94) style:UITableViewStylePlain];
        _categoryTableView.delegate = self;
        _categoryTableView.dataSource = self;
        _categoryTableView.separatorColor = [UIColor clearColor];
        _categoryTableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
        [self.view addSubview:_categoryTableView];
    }
    return _categoryTableView;
}

- (UICollectionView *)categoryCollectionView{
    if (!_categoryCollectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        _categoryCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(TableViewWidth, 108, SCREEN_WIDTH - TableViewWidth, SCREEN_HEIGHT - 64 - 94) collectionViewLayout:layout];
        _categoryCollectionView.backgroundColor = [UIColor clearColor];
        _categoryCollectionView.delegate = self;
        _categoryCollectionView.dataSource = self;
        _categoryCollectionView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_categoryCollectionView];
    }
    return _categoryCollectionView;
}


@end